<template>
  <div>
      <div class="face_header">
          <p style='width: 95%; text-align:center'>
              <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft" /></p>
      </div>
      <h3 class="header-text">人脸登录验证</h3>
      <div class="face_container">
          <video ref="videoRef" class="video-element"></video>
      </div>
      <div class="face_container_1">
          <canvas ref="canvasRef" class="canvas-element"></canvas>
      </div>
      <div style="width:250px;">
          <button @click="capture" style="width:100px;height:40px;background-color: rgb(36, 153, 248);color: white;border-radius: 5px;">捕获图像</button>
          <button :disabled="flag || flag1" @click="submitImages" style="width:100px;height:40px;background-color: rgb(36, 153, 248);color: white;border-radius: 5px;margin-left: 10px;">登录</button>
      </div>
      <p v-if="flag" class="success-message">登录成功！正在跳转...</p>
      <p v-if="flag1" class="error-message">登录失败，请重试。</p> 
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const flag = ref(false);
const flag1 = ref(false);
const videoRef = ref(null);
const canvasRef = ref(null);
let stream; // Declare stream variable to manage video feed
let router = useRouter();
const onClickLeft = () => history.back();
// Start camera function
const startCamera = async () => {
  try {
      stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (videoRef.value) {
          videoRef.value.srcObject = stream;
          videoRef.value.play();
      }
  } catch (error) {
      console.error('访问摄像头出错：', error);
  }
};

// Close camera function
const closeMedia = () => {
  if (stream) {
      const tracks = stream.getTracks();
      tracks.forEach(track => track.stop()); // Stop each track
  }
};

// Capture image function
const capture = () => {
  if (!canvasRef.value || !videoRef.value) return;

  const canvas = canvasRef.value;
  const context = canvas.getContext('2d');
  context.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height);

  const imageSrc = canvas.toDataURL('image/jpeg');
  submitImages(imageSrc); // Directly submit the captured image
};

// Submit images function
const submitImages = async (img) => {
  try {
      const res = await axios.post('http://127.0.0.1:3000/jsb/faceLogin', { b64: img });
      handleResponse(res.data);
  } catch (error) {
      console.error('提交图像出错', error);
      flag1.value = true;
  }
};

// Handle server response
const handleResponse = (data) => {
  if (data.code === 200) {
      flag.value = true;
      setTimeout(() => {
          flag.value = false;
          router.push('/bindtel'); // Assuming `navigate` is defined elsewhere
      }, 2000);
  } else if (data.code === 401) {
      flag1.value = true;
      setTimeout(() => {
          flag1.value = false;
      }, 2000);
  }
};

onMounted(() => {
  startCamera();
});

onBeforeUnmount(() => {
  closeMedia(); // Clean up camera resources on component unmount
});
</script>

<style lang="scss" scoped>
.face_header {
  width: 100vw;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  box-sizing: border-box;
  border-bottom: 1px solid #f1f1f1;
}

.header-text {
  padding-left: 35px;
  margin-top: 10px;
  margin-bottom: -15px;
}

.face_container {
  border: 1px solid black;
  width: 50vw;
  height: 50vw;
  overflow: hidden;
  position: relative;
  border-radius: 50%;
  margin: 50px auto;

}
.face_container_1 {
  width: 50vw;
  height: 50vw;
  overflow: hidden;
  position: relative;
  border-radius: 50%;
  margin: 50px auto;

}

.video-element {
  width: 150%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: -45px;

}

.canvas-element {
  width: 150%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: -45px;
}

.success-message {
  color: green;
  padding-left: 35px;
}
</style>
